<template>
  <div class="node-edit-panel-container">
    <div v-show="spinning" class="loading"><a-spin :spinning="spinning" /></div>
    <operator-parameter v-show="isShowOperatorParameter" />
    <div class="left-supercontainer">
      <!-- 头部 -->
      <div class="left-header">
        <!-- tabs -->
        <node-tabs
          v-if="isShowTabs"
          v-model="activeTabId"
          :min-hidden-width="70"
          :tabs="nodeTabs"
          @change-tab="changeTab"
        />
        <!-- 正常显示 -->
        <template v-if="!isShowTabs">
          {{ selectNode ? selectNode.name : '' }}
          <span v-if="columnCount > 0" class="count-info"
            >共有{{ columnCount }}个字段, {{ dataNumberCount }}行</span
          >
          <a-icon-font
            v-show="selectNode.type === 5"
            type="iconqingxi-caozuojilu"
            :class="{ 'icon-history': true, active: isShowHistory }"
            @click="toggleHistoryMode()"
          />
        </template>

        <div
          v-show="selectedColumns.length > 1 && !isVisitor && !isLock"
          class="btn btn-merge-col"
          @click="activeMergeColumn"
        >
          合并字段
        </div>
        <!-- 全局搜索 -->
        <global-search v-if="hiddenSearchDownloadIcon" />
        <!-- 全屏 -->
        <a-icon-font
          :type="
            panelFullScreen ? 'icontuichuquanping' : 'iconfangdahuabanquanping'
          "
          title="全屏"
          :style="{ right: hiddenSearchDownloadIcon ? '48px' : '20px' }"
          class="icon-full-screen"
          @click="fullScreen"
        ></a-icon-font>
        <a-icon-font
          v-show="
            isShowExport && !isVisitor && !isLock && hiddenSearchDownloadIcon
          "
          type="iconbaocun"
          title="导出"
          class="icon-export"
          @click="onExport"
        ></a-icon-font>
      </div>
      <div
        v-show="
          ['CREATE', 'RUNNING'].includes((selectNode.data || {}).isSample)
        "
        class="progress-bar"
      ></div>
      <div class="left-main">
        <history-list
          v-show="isShowHistory"
          :is-show-history="isShowHistory"
          @toggle-history-mode="(value) => (isShowHistory = value)"
          @change-history="onChangeHistory"
        />
        <div class="middle-container">
          <!-- 提示信息 高度 36 -->
          <div
            v-show="showPrompt && showTaskPromptText"
            class="prompt-information"
          >
            <div class="prompt-information-content">
              <div class="prompt-information-text">
                <span :title="showTaskPromptText">
                  {{ showTaskPromptText }}
                </span>
              </div>
              <a-icon-font
                type="iconicon-beifen1-copy"
                class="close-prompt"
                @click="closeTaskShowPrompt"
              />
            </div>
          </div>

          <template v-if="isShowTabs">
            <!-- 列卡片 -->
            <data-columns
              v-if="activeTabId === 2"
              :is-visitor="
                isVisitor ||
                isLock ||
                (selectNode.data && selectNode.data.forbidden)
              "
              class="data-columns"
            />
            <!-- 数据表 -->
            <data-table
              v-if="activeTabId === 2"
              ref="nodeEditPanelTable"
              class="data-table"
            />
            <operator-chart v-if="activeTabId === 1" />
          </template>
          <template v-else>
            <!-- 列卡片 -->
            <data-columns
              ref="dataColumns"
              :is-visitor="
                isVisitor ||
                isLock ||
                (selectNode.data && selectNode.data.forbidden)
              "
              class="data-columns"
            />
            <!-- 数据表 -->
            <data-table class="data-table" />
          </template>
        </div>
      </div>
    </div>
    <!-- <data-visualization /> -->
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch, Prop } from 'vue-property-decorator'
import HistoryList from '@/components/studio/data/node-edit-panel/HistoryList.vue'
import DataVisualization from '@/components/studio/data/node-edit-panel/DataVisualization.vue'
import OperatorParameter from '@/components/studio/data/node-edit-panel/OperatorParameter.vue'
import DataTable from '@/components/studio/data/node-edit-panel/DataTable.vue'
import DataColumns from '@/components/studio/data/node-edit-panel/DataColumns.vue'
import GlobalSearch from '@/components/studio/data/node-edit-panel/GlobalSearch.vue'
import NodeTabs from '@/components/studio/data/node-edit-panel/operator-chart/NodeTabs.vue'
import OperatorChart from '@/components/studio/data/node-edit-panel/operator-chart/OperatorChart.vue'
import DataViewStore, { EditActionArea } from '@/store/modules/dataview'
import {
  setWatermark,
  deleteWatermark,
  removeResizeListener,
} from '@/util/util'
import UserStore from '@/store/modules/user'
import { baseURL } from '@/api/axios-config'
// @ts-ignore
const elementResizeDetectorMaker = require('element-resize-detector')

@Component({
  components: {
    HistoryList,
    DataVisualization,
    OperatorParameter,
    DataTable,
    DataColumns,
    GlobalSearch,
    NodeTabs,
    OperatorChart,
  },
})
export default class NodeEditPanel extends Vue {
  private isShowHistory: boolean = false
  private erd: any
  private middleContainer: any
  private spinning: boolean = false

  @Prop({ type: Boolean, default: false }) panelFullScreen!: boolean

  // tabs 经济算子 有需要显示图表的
  public get nodeTabs(): any[] {
    return [
      { id: 1, name: `${this.selectNode.name}-可视化` },
      { id: 2, name: `${this.selectNode.name}-结果表` },
    ]
  }
  // 当前激活的tab
  public activeTabId: number = 1

  // 经济算子， 有图表tab  搜索，下载 icon
  public get hiddenSearchDownloadIcon() {
    return !(this.isShowTabs && this.activeTabId === 1)
  }

  // 节点运行信息提示
  public get showPrompt(): boolean {
    return DataViewStore.showTaskPrompt
  }

  // 显示提示消息， 调整数据详情表高度
  @Watch('showPrompt')
  public watchShowPrompt(value: boolean) {
    DataViewStore.setTableHeight(
      DataViewStore.nodeEditPanelHeight - 38 - 270 - 5 - (value ? 36 : 0)
    )
  }

  public get showTaskPromptText() {
    return DataViewStore.showTaskPromptText
  }

  // 全屏
  public fullScreen() {
    this.$emit('toggle-full-screen')
  }

  public closeTaskShowPrompt() {
    DataViewStore.setShowTaskPrompt(false)
  }

  public get isShowTabs() {
    if (this.selectNode.id) {
      const { type, data } = this.selectNode
      const { algType } = data
      // 1-异常值识别， 6-时间序列, 7-数据平滑， 显示图表
      return type === 8 && [1, 2, 6, 7, 10].includes(Number(algType))
    }
    return false
  }

  public changeTab(tab: any) {
    this.activeTabId = tab.id
  }

  private get selectNode() {
    return DataViewStore.selectNode || {}
  }

  private get isShowExport() {
    return true
    // return [1, 2].includes(+this.selectNode.type) // 算子节点才出现
  }

  private get isTableDetailLoading() {
    return DataViewStore.isTableDetailLoading
  }

  public get isVisitor() {
    return DataViewStore.isVisitor
  }

  public get isLock() {
    return DataViewStore.getLock
  }

  get columnCount() {
    return DataViewStore.tableColumns.length
  }

  private get isShowOperatorParameter() {
    return !this.isVisitor && !this.isLock && !this.selectNode.data?.forbidden // forbidden 节点禁用
  }

  // 后台接口变更，现在从output中取
  get dataNumberCount() {
    return DataViewStore.tableDataCount
    // if (this.selectNode.type === 5) { // 清洗节点从数据详情中获取
    //   return DataViewStore.tableDataCount
    // }
    // return this.selectNode?.data?.output[0].totalRow as number || 0
  }

  @Watch('selectNode')
  private onSelectNodeChange(newValue: any) {
    this.isShowHistory = newValue.type === 5 // 清洗节点默认展开，其余类型节点不展示
    DataViewStore.setVRPanelShow(false)
    this.selectNodeIdChange(this.selectNode.id)
    DataViewStore.setSelectedColumns([])
    if (!newValue) {
      this.spinning = false
    }

    this.configureActionArea(newValue)
  }

  // 节点 id 变化 关闭提示框
  public oldSelectId: any = null
  public selectNodeIdChange(id: any) {
    if (id !== this.oldSelectId) {
      DataViewStore.dealNodePrompt()
    }
    this.oldSelectId = id
  }

  private configureActionArea(value: any) {
    const keyArray = Object.keys(value)
    if (keyArray.length === 0) {
      DataViewStore.setActionArea(EditActionArea.PIPELINE)
    } else {
      DataViewStore.setActionArea(EditActionArea.PANEL)
    }
  }

  @Watch('isTableDetailLoading')
  private onIsTableDetailLoading() {
    this.spinning = this.isTableDetailLoading
  }

  private get selectedColumns() {
    return DataViewStore.selectedColumns
  }

  toggleHistoryMode() {
    this.isShowHistory = !this.isShowHistory
  }

  activeMergeColumn() {
    DataViewStore.setMergeColumnHotKey(true)
  }

  public mounted() {
    const self = this
    this.erd = elementResizeDetectorMaker({
      strategy: 'scroll', //  <- For ultra performance.
      callOnAdd: false,
    })
    this.middleContainer = document.querySelector(
      '.middle-container'
    ) as HTMLElement
    this.erd.listenTo(this.middleContainer, () => {
      self.$nextTick(() => {
        // 监听到事件后执行的业务逻辑
        const areaName = '.middle-container'
        setWatermark(this.username, areaName)
      })
    })
  }

  public get username() {
    return UserStore.currentUser ? UserStore.currentUser.name : '未命名用户'
  }

  public onExport() {
    if (this.columnCount === 0) {
      this.$message.warning('当前表暂无数据，无法导出')
      return
    }
    window.open(`${baseURL}/task/download?taskId=${this.selectNode.id}`)
  }

  private onChangeHistory() {
    if (
      this.$refs.dataColumns &&
      typeof (this.$refs.dataColumns as any).scrollLeft === 'function'
    ) {
      ;(this.$refs.dataColumns as any).scrollLeft(0)
    }
  }

  beforeDestroy() {
    deleteWatermark('water_mark')
    removeResizeListener()
    this.erd.uninstall(this.middleContainer)
  }
}
</script>

<style lang="less" scoped>
.node-edit-panel-container {
  background: #f0f2f5;
  display: flex;
  height: 100%;
  position: relative;

  .loading {
    align-items: center;
    background-color: rgba(255, 255, 255, 0.6);
    bottom: 0;
    display: flex;
    justify-content: center;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 999;
  }

  .count-info {
    color: #222432;
    font-family: '微软雅黑', SimSun, '宋体', Heiti, '黑体', sans-serif;
    font-size: 12px;
    letter-spacing: 1.12px;
    margin-left: 8px;
    opacity: 0.5;
  }

  .left-supercontainer {
    flex: 1;
    flex-direction: column;
    min-width: 0;
    overflow-y: hidden;

    .left-header {
      background: #eff0f7;
      border-left: 1px solid #e9e9e9;
      border-right: 1px solid #e9e9e9;
      flex: 0 0 38px;
      height: 38px;
      line-height: 38px;
      padding: 0 16px;
      position: relative;

      .icon-history {
        color: #5d637e;
        cursor: pointer;
        font-size: 14px;
        margin-left: 12px;
        padding: 7px 10px;

        &.active {
          background-color: #e1e3fd;
          color: #6973ff;
        }
      }

      .icon-export {
        cursor: pointer;
        font-size: 16px;
        position: absolute;
        right: 20px;
        top: 11px;
      }

      .icon-full-screen {
        cursor: pointer;
        font-size: 16px;
        position: absolute;
        top: 11px;
      }

      .btn {
        cursor: pointer;
        display: inline-block;
      }

      .fullScreen-button {
        background-color: #eff0f7;
        border-color: #eff0f7;
        box-shadow: none;
        color: #666;
        font-size: 16px;
        height: 20px;
        line-height: 20px;
        opacity: 0.8;
        padding: 0 4px;
        position: absolute;
        right: 48px;
        top: 10px;
        width: 22px;
        z-index: 9;

        &:hover {
          opacity: 1;
        }
      }
    }

    .left-main {
      display: flex;
      flex: 1;
      height: calc(100% - 38px);

      .left-container {
        background: #fff;
        flex: 0 0 280px;
      }

      .middle-container {
        background: #fafafc;
        display: flex;
        flex: 1;
        flex-direction: column;
        min-width: 0;
        position: relative;

        // 节点提示信息
        .prompt-information {
          border-left: 1px solid #e9e9e9;
          flex-shrink: 0;
          height: 36px;

          .prompt-information-content {
            align-items: center;
            background: #fff1f0;
            border: 1px solid #ffa39e;
            display: flex;
            height: 32px;
            justify-content: space-between;
            line-height: 32px;
            margin-top: 4px;
            padding: 0 19px;
            width: 100%;

            .prompt-information-text {
              max-width: calc(100% - 24px);
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }

            .close-prompt {
              cursor: pointer;
            }
          }
        }

        .data-columns {
          flex: 0 0 266px;
        }

        .data-table {
          flex: 1;
        }
      }
    }

    .progress-bar {
      animation: gradient 1.5s ease infinite;
      background: linear-gradient(
        90deg,
        #c0bfff78 25%,
        #5760e6 37%,
        #c0bfff78 63%
      );
      background-size: 400% 100%;
      height: 3px;
      width: 100%;
    }
  }

  .right-container {
    background: #fff;
    flex: 0 0 225px;
  }
}

@keyframes gradient {
  0% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}
</style>
